<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户来源" prop="sourceId">
        <el-select
          v-model="queryParams.sourceId"
          placeholder="请选择客户来源"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_CUSTOMER_SOURCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属行业" prop="industryId">
        <el-select
          v-model="queryParams.industryId"
          placeholder="请选择所属行业"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_INDUSTRY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户等级" prop="levelId">
        <el-select
          v-model="queryParams.levelId"
          placeholder="请选择客户等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_CUSTOMER_LEAVE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户意向" prop="intentId">
        <el-select
          v-model="queryParams.intentId"
          placeholder="请选择客户意向"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_INTENT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['oa:customer:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['oa:customer:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleImport"
          v-hasPermi="['oa:customer:create']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
      <el-button type="primary" @click="handleDownloadTemplate">
        <Icon icon="ep:download" class="mr-5px" />下载模板
      </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="客户名称" align="center" prop="customerName" width="150" />
      <el-table-column label="联系人" align="center" prop="contactName" width="100" />
      <el-table-column label="联系电话" align="center" prop="phone" width="120" />
      <el-table-column label="电子邮箱" align="center" prop="email" width="150" />
      <el-table-column label="客户等级" align="center" prop="levelId">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_CUSTOMER_LEAVE" :value="scope.row.levelId" />
        </template>
      </el-table-column>
      <el-table-column label="客户来源" align="center" prop="sourceId" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_CUSTOMER_SOURCE" :value="scope.row.sourceId" />
        </template>
      </el-table-column>
      <el-table-column label="所属行业" align="center" prop="industryId" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.OA_INDUSTRY" :value="scope.row.industryId" />
        </template>
      </el-table-column>
      
      <el-table-column label="创建者" align="center" prop="creatorName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="350px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleDetail(scope.row.id)"
            v-hasPermi="['oa:customer:query']"
          >
            查看
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['oa:customer:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['oa:customer:delete']"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleAssign(scope.row)"
            v-hasPermi="['oa:customer:update']"
          >
            分配
          </el-button>
          <el-button
            link
            type="success"
            @click="handleReceive(scope.row)"
            v-hasPermi="['oa:customer:update']"
          >
            领取
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleMoveToTrash(scope.row)"
            v-hasPermi="['oa:customer:update']"
          >
            转入废弃池
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />
  <!-- 详情弹窗 -->
  <CustomerDetail ref="detailRef" />
  <!-- 分配弹窗 -->
  <Dialog v-model="assignDialogVisible" title="分配客户" width="500px">
    <el-form ref="assignFormRef" :model="assignForm" label-width="80px">
      <el-form-item label="选择用户" prop="recipientId">
        <user-select v-model="assignForm.recipientId" @node-change="handleUserChange" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitAssign">确 定</el-button>
      <el-button @click="assignDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 导入弹窗 -->
  <Dialog v-model="importDialogVisible" title="导入客户" width="400px">
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      :show-file-list="true"
      :limit="1"
      :on-exceed="handleExceed"
      :on-change="handleFileChange"
      :file-list="fileList"
      accept=".xlsx, .xls"
    >
      <template #trigger>
        <el-button type="primary">选择文件</el-button>
      </template>
      <template #tip>
        <div class="el-upload__tip">
          请上传 .xlsx 或 .xls 格式的 Excel 文件
        </div>
      </template>
    </el-upload>
    <div class="mt-10px">
      <el-button link type="primary" @click="handleDownloadTemplate">
        <Icon icon="ep:download" class="mr-5px" />下载模板
      </el-button>
    </div>
    <template #footer>
      <el-button type="primary" @click="submitImport" :loading="importLoading">确 定</el-button>
      <el-button @click="importDialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/oa/customer'
import CustomerForm from './CustomerForm.vue'
import CustomerDetail from './CustomerDetail.vue'
import UserSelect from '@/views/system/user/UserSelect.vue'
import { useUserStore } from '@/store/modules/user'

/** 客户基本信息 列表 */
defineOptions({ name: 'Customer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStore() // 用户store

const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerName: undefined,
  sourceId: undefined,
  industryId: undefined,
  levelId: undefined,
  intentId: undefined,
  gender: undefined,
  statusId: 0,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const formRef = ref() // 表单 Ref
const detailRef = ref() // 详情 Ref

// 分配相关
const assignDialogVisible = ref(false)
const assignFormRef = ref()
const assignForm = reactive({
  id: undefined as number | undefined,
  recipientId: undefined as number | undefined,
  recipientName: '',
})

// 导入相关
const importDialogVisible = ref(false)
const importLoading = ref(false)
const uploadRef = ref()
const fileList = ref<any[]>([])
const importFile = ref<File>()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 查看详情操作 */
const handleDetail = (id: number) => {
  detailRef.value?.open(id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, '客户基本信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 处理分配按钮点击 */
const handleAssign = (row: CustomerVO) => {
  assignForm.id = row.id
  assignForm.recipientId = undefined
  assignForm.recipientName = ''
  assignDialogVisible.value = true
}

/** 处理用户选择变化 */
const handleUserChange = (user: any) => {
  assignForm.recipientName = user.nickname
}

/** 提交分配 */
const submitAssign = async () => {
  if (!assignForm.recipientId) {
    message.warning('请选择要分配的用户')
    return
  }
  try {
    await CustomerApi.assignCustomer({
      id: assignForm.id!,
      recipientId: assignForm.recipientId,
      recipientName: assignForm.recipientName
    })
    message.success('分配成功')
    assignDialogVisible.value = false
    await getList()
  } catch {}
}

/** 处理领取按钮点击 */
const handleReceive = async (row: CustomerVO) => {
  try {
    await CustomerApi.assignCustomer({
      id: row.id,
      recipientId: userStore.getUser.id,
      recipientName: userStore.getUser.nickname
    })
    message.success('领取成功')
    await getList()
  } catch {}
}

/** 处理导入按钮点击 */
const handleImport = () => {
  importDialogVisible.value = true
  fileList.value = []
  importFile.value = undefined
}

/** 处理文件超出限制 */
const handleExceed = () => {
  message.warning('最多只能上传一个文件')
}

/** 处理文件变化 */
const handleFileChange = (file: any) => {
  importFile.value = file.raw
}

/** 提交导入 */
const submitImport = async () => {
  if (!importFile.value) {
    message.warning('请选择要导入的文件')
    return
  }
  try {
    importLoading.value = true
    const formData = new FormData()
    formData.append('file', importFile.value)
    await CustomerApi.importCustomer(formData)
    message.success('导入成功')
    importDialogVisible.value = false
    await getList()
  } catch {
  } finally {
    importLoading.value = false
  }
}

/** 下载模板 */
const handleDownloadTemplate = async () => {
  try {
    const res = await CustomerApi.importCustomerTemplate()
    download.excel(res, '客户导入模板.xlsx')
  } catch (error) {
    console.error('下载模板失败:', error)
  }
}

/** 处理转入废弃池 */
const handleMoveToTrash = async (row: CustomerVO) => {
  try {
    await message.confirm('确认将该客户转入废弃池吗？')
    await CustomerApi.moveToTrash(row.id,-1)
    message.success('转入废弃池成功')
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>